import { bindAccountQueryByPhone, bindAccountOrganization, loginWxampForWechatBindingAccount } from "../../service/api/api-login";
import { fontSizeCalc, handleErrCode, loginCallback } from "../../utils/util";

// pages/bind/index.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isLoading: false,//节流阀
    bindState: 0,//状态
    alertMessage: "",
    submitText: "",
    phone: '',// 手机号
    name: '',// 姓名
    organizations: [],// 组织列表
    organization: undefined,// 已选的组织
    iconSize: fontSizeCalc(30),
    labelSize: fontSizeCalc(32),
    inputSize: fontSizeCalc(32),
    btnHeight: fontSizeCalc(96) + 'rpx',
    btnLineHeight: fontSizeCalc(70) + 'rpx',
  },

  onShow() {
    wx.hideHomeButton();
    wx.hideShareMenu({
      menus: ['shareAppMessage', 'shareTimeline'],// 隐藏分享到朋友和分享到朋友圈
    })
  },

  /**
   * 点击事件 绑定账户（登录）
   */
  onFormSubmitBind() {

    let that = this;

    if (that.data.bindState == 10) {
      //重新输入
      that.setData({
        bindState: 0,
        phone: ''
      })

      that.onLoadAlertMessage();

    } else {

      // 校验手机号码
      if (!new RegExp(/^1\d{10}$/).test(this.data.phone)) {
        wx.showToast({
          title: '手机号输入有误，请重新输入',
          icon: 'none',
          duration: 1500
        })
        return
      }
      that.setData({ isLoading: true });
      wx.showLoading({
        title: this.data.submitText + '中...'
      })
      wx.showNavigationBarLoading();

      if (this.data.bindState === 0) {


        wx.login({
          success: loginRes => {
            bindAccountQueryByPhone({
              phone: that.data.phone,
              code: loginRes.code,
            }).then(async (response) => {

              let bindState = response.data.bindState
              if (bindState === 1) {
                await bindAccountOrganization().then(res => {
                  if (res?.data) {
                    this.setData({
                      organizations: Array.isArray(res.data) && this.readyTreeData(res?.data) || [],
                    })
                  }
                })
              } else {

              }
              this.setData(
                { bindState: bindState, isLoading: false }
              )
              this.onLoadAlertMessage();
              wx.hideNavigationBarLoading();
              wx.hideLoading();
            })
          },
        })


      } else {

        if (this.data.bindState === 1) {
          if (this.data.name === undefined || this.data.name === "") {
            wx.showToast({
              title: '请输入姓名',
              icon: 'none',
              duration: 1500
            })
            return
          }

          if (this.data.organization === undefined) {
            wx.showToast({
              title: '请选择组织',
              icon: 'none',
              duration: 1500
            })
            return
          }

          if (this.data.organization.isFolder === 1 || this.data.organization.isChildren === 1) {
            wx.showToast({
              title: '请选择组织',
              icon: 'none',
              duration: 1500
            })
            return
          }
        }

        wx.login({
          success: loginRes => {
            loginWxampForWechatBindingAccount({
              serviceName: "cqgxq",
              code: loginRes.code,
              phone: that.data.phone,
              name: that.data.name,
              organizationIds: [this.data.organization ? that.data.organization.value : ""],
            }).then(async (response) => {
              if (response?.code === 0) {
                if (response?.data) {
                  loginCallback(response)
                }
              } else {
                handleErrCode(response?.msg)
              }
            }).catch(error => {
              handleErrCode(error, 'none')
            }).finally(() => {
              that.setData({ isLoading: false });
              wx.hideNavigationBarLoading();
              wx.hideLoading();
            })
          },
        })
      }

    }
  },


  onLoadAlertMessage() {
    let alertMessage = "";
    let submitText = "";
    let secTitle = "";

    /**
     * 状态
     * 1、无账号
     * 2、有账号，未绑定
     * 3、有账号，已绑定，未激活
     * 4、有账号、已绑定，有激活、未启用
     * 5、有账号、已绑定，有激活、已启用
     */

    switch (this.data.bindState) {
      case 0:
        alertMessage = '请填写手机号，查询账户状态';
        submitText = '查询';
        break;
      case 1:
        alertMessage = '填写所有信息，提交后待管理员审核后完成注册流程。';
        submitText = '注册';
        break;
      case 2:
        alertMessage = '管理员已为您添加好了账户，输入手机号完成绑定操作';
        submitText = '绑定';
        break;
      case 3:
        alertMessage = '管理员已为您添加好了账户，输入手机号完成激活操作';
        submitText = '激活';
        break;
      case 4:
        alertMessage = '管理员已为您添加好了账户，输入手机号完成启用操作';
        submitText = '启用';
        break;
      case 5:
        alertMessage = '管理员已为您完成了账号注册，请直接使用';
        secTitle = '完成注册';
        submitText = '进入首页';
        break;
      case 10:
        alertMessage = '该手机号已经被其他微信账号绑定';
        secTitle = '注册';
        submitText = '重新输入';
        break;
      default:
        alertMessage = '';
        submitText = '';
        break;
    }

    this.setData({
      alertMessage, submitText
    })
    wx.setNavigationBarTitle({
      title: secTitle || submitText,
    })
  },
  async onLoad() {
    this.onLoadAlertMessage();
  },

  /**
   * 预备Tree结构数据
   * @param data
   */
  readyTreeData(data: AdminOrganizationData.Organization[]): any {
    const treeData = [];
    if (data) {
      data.forEach((val) => {

        if (val.isFolder === 1 && val.children === undefined) {

        } else {
          treeData.push({
            text: val.name,
            value: val.id,
            isFolder: val.isFolder,
            disabled: val.isFolder === 1 && val.children === undefined ? 0 : 1,
            isChildren: val.children === undefined ? 0 : 1,
            children: this.readyTreeData(val.children as AdminOrganizationData.Organization[]),
          });
        }
      });
    }
    return treeData;
  },

  /**
   * 联级选择 修改
   */
  cascadeChange(res: { detail: any; }) {
    const detail = res?.detail;

    console.log(detail);

    this.setData({
      organization: detail
    })
  },
})